/**
 * Copyright (c) 2020 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */
package io.renren.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.commons.mybatis.service.impl.CrudServiceImpl;
import io.renren.demo.dao.WorkOrderDao;
import io.renren.demo.entity.WorkOrderEntity;
import io.renren.demo.service.ProdDetailService;
import io.renren.demo.service.WorkOrderService;
import io.renren.dto.ProdDetailDTO;
import io.renren.dto.WorkOrderDTO;
import io.renren.feign.UserFeignClient;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * 工单审批
 *
 * @author Mark sunlightcs@gmail.com
 */
@Service
public class WorkOrderServiceImpl extends CrudServiceImpl<WorkOrderDao, WorkOrderEntity, WorkOrderDTO> implements WorkOrderService {
    @Autowired
    private ProdDetailService prodDetailService;
    @Override
    public QueryWrapper<WorkOrderEntity> getWrapper(Map<String, Object> params){
        return null;
    }

    @Override
    public void updateInstanceId(String instanceId, Long id) {
        baseDao.updateInstanceId(instanceId, id);
    }

    @Override
    public WorkOrderDTO get(Long id) {
        WorkOrderEntity entity =baseDao.selectById(id);
        WorkOrderDTO dto=new WorkOrderDTO();
        if(BeanUtil.isNotEmpty(entity)){
            BeanUtil.copyProperties(entity,dto);
        }
        dto.setProdDetailDTOList(prodDetailService.getByWorkOrderId(id));
        return dto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(WorkOrderDTO dto) {
        super.save(dto);
        if(BeanUtil.isNotEmpty(dto.getId())){
            for(ProdDetailDTO prodDetailDTO:dto.getProdDetailDTOList()){
                prodDetailDTO.setWorkOrderId(dto.getId());
            }
            prodDetailService.addProdDetails(dto.getProdDetailDTOList());

        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(WorkOrderDTO dto) {
        super.update(dto);
        if(BeanUtil.isNotEmpty(dto.getId())){
            prodDetailService.deleteByWorkOrderId(dto.getId());
            for(ProdDetailDTO prodDetailDTO:dto.getProdDetailDTOList()){
                prodDetailDTO.setWorkOrderId(dto.getId());
            }
            prodDetailService.addProdDetails(dto.getProdDetailDTOList());
        }
    }
}